/*********************************
 * jsmud: JavaScript MUD Kernel  *
 *          Mojodo, Inc.         *
 *        Sean Middleditch       *
 * Copyright (C) 2005,2007,2008  *
 *      All rights reserved.     *
 *   See COPYING for licensing.  *
 *********************************/

/* ==== SYSTEM INCLUDES ==== */

#include <string.h>
#include <errno.h>
#include <limits.h>
#include <arpa/telnet.h>
#include <sys/stat.h>

/* ==== LIBRARY INCLUDES ==== */

#include <sqlite3.h>
#include <zlib.h>

#define XP_UNIX 1
#define MOZILLA_1_8_BRANCH 1
#include <jsapi.h>
#undef XP_UNIX
#undef MOZILLA_1_8_BRANCH

/* ==== JSMUD HEADER ==== */

#include "jsmud.h"

/* ==== SCRIPT BINDINGS ==== */

/* -- GLOBAL -- */

JSAPI(js_log);
JSAPI(js_error);
JSAPI(js_getsetting);
JSAPI(js_include);
JSAPI(js_exit);

static JSFunctionSpec js_global_functions[] = {
	{"include", js_include, 1, 0, 0},
	{"log", js_log, 1, 0, 0},
	{"error", js_error, 1, 0, 0},
	{"getSetting", js_getsetting, 2, 0, 0},
	{"exit", js_exit, 0, 0, 0},
	{NULL, 0, 0, 0, 0}
};

JSAPI(js_log)
{
	JSString* string;

	if ((string = JS_ValueToString(cx, argv[0])) == NULL)
		return JS_FALSE;
	log_msg("%s", JS_GetStringBytes(string));

	return JS_TRUE;
}

JSAPI(js_error)
{
	JSString* string;

	if ((string = JS_ValueToString(cx, argv[0])) == NULL)
		return JS_FALSE;
	log_error("%s", JS_GetStringBytes(string));

	return JS_TRUE;
}

JSAPI(js_getsetting)
{
	JSString* string;
	const char* name;
	Setting* setting;

	if ((string = JS_ValueToString(cx, argv[0])) == NULL)
		return JS_FALSE;
	name = JS_GetStringBytes(string);

	for (setting = opt_custom; setting != NULL; setting = setting->next) {
		if (!strcmp(setting->name, name)) {
			string = JS_NewStringCopyZ(cx, setting->value);
			if (string == NULL)
				return JS_FALSE;
			*rval = STRING_TO_JSVAL(string);
			return JS_TRUE;
		}
	}

	*rval = argv[1];

	return JS_TRUE;
}

JSAPI(js_include)
{
	JSString* string;
	const char* path;
	JSScript* script;

	/* convert path to a string (store reference in argv for gc-safety) */
	if ((string = JS_ValueToString(cx, argv[0])) == NULL)
		return JS_FALSE;
	argv[0] = STRING_TO_JSVAL(string);
	path = JS_GetStringBytes(string);

	/* load the script */
	if ((script = JS_CompileFile(cx, JS_GetGlobalObject(cx), makepath(path))) == NULL)
		return JS_FALSE;
	if (!JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, rval))
		return JS_FALSE;

	return JS_TRUE;
}

JSAPI(js_exit)
{
	exit_flag = 1;
	return JS_TRUE;
}

/* ==== INITIALIZE BINDINGS ==== */

int init_stdlib (void)
{
	if (!JS_DefineFunctions(js_context, js_global, js_global_functions)) {
		log_error("JS_DefineFunctions() failed");
		return 0;
	}

	return 1;
}

/* vim: set tabstop=2 shiftwidth=2 ai: */
